<template>
  <div class="stats-container">
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>绩效统计</h2>
          <div class="filter-actions">
            <el-button-group>
              <el-button :type="timeRange === 'day' ? 'primary' : ''" @click="timeRange = 'day'">今日</el-button>
              <el-button :type="timeRange === 'week' ? 'primary' : ''" @click="timeRange = 'week'">本周</el-button>
              <el-button :type="timeRange === 'month' ? 'primary' : ''" @click="timeRange = 'month'">本月</el-button>
              <el-button :type="timeRange === 'quarter' ? 'primary' : ''" @click="timeRange = 'quarter'">本季度</el-button>
              <el-button :type="timeRange === 'year' ? 'primary' : ''" @click="timeRange = 'year'">本年</el-button>
            </el-button-group>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="default"
              @change="handleDateRangeChange"
            />
            <el-button type="success" @click="exportData">
              <el-icon><Download /></el-icon>导出数据
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="filter-form">
        <el-form :model="filterForm" :inline="true">
          <el-form-item label="区域">
            <el-cascader
              v-model="filterForm.region"
              :options="regionOptions"
              placeholder="选择区域"
              clearable
            />
          </el-form-item>
          <el-form-item label="业务类型">
            <el-select v-model="filterForm.businessType" placeholder="选择业务类型" clearable>
              <el-option label="标准快递" value="standard" />
              <el-option label="特快专递" value="express" />
              <el-option label="经济快递" value="economy" />
            </el-select>
          </el-form-item>
          <el-form-item label="统计维度">
            <el-select v-model="filterForm.dimension" placeholder="选择统计维度">
              <el-option label="订单数量" value="orderCount" />
              <el-option label="营业额" value="revenue" />
              <el-option label="毛利润" value="profit" />
              <el-option label="客户数量" value="customerCount" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilter">应用筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <!-- 核心数据指标卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>总订单数</h3>
            <div class="stat-number">{{ formatNumber(statData.totalOrders) }}</div>
            <div class="stat-trend" :class="statData.ordersTrend > 0 ? 'up' : 'down'">
              <el-icon><component :is="statData.ordersTrend > 0 ? ArrowUp : ArrowDown" /></el-icon>
              <span>{{ Math.abs(statData.ordersTrend) }}%</span>
              <span class="trend-period">较上期</span>
            </div>
          </div>
          <div class="stat-icon orders">
            <el-icon><Tickets /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>总收入</h3>
            <div class="stat-number">¥{{ formatNumber(statData.totalRevenue) }}</div>
            <div class="stat-trend" :class="statData.revenueTrend > 0 ? 'up' : 'down'">
              <el-icon><component :is="statData.revenueTrend > 0 ? ArrowUp : ArrowDown" /></el-icon>
              <span>{{ Math.abs(statData.revenueTrend) }}%</span>
              <span class="trend-period">较上期</span>
            </div>
          </div>
          <div class="stat-icon revenue">
            <el-icon><Money /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>平均单价</h3>
            <div class="stat-number">¥{{ formatNumber(statData.averageOrderValue) }}</div>
            <div class="stat-trend" :class="statData.aovTrend > 0 ? 'up' : 'down'">
              <el-icon><component :is="statData.aovTrend > 0 ? ArrowUp : ArrowDown" /></el-icon>
              <span>{{ Math.abs(statData.aovTrend) }}%</span>
              <span class="trend-period">较上期</span>
            </div>
          </div>
          <div class="stat-icon aov">
            <el-icon><PriceTag /></el-icon>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-info">
            <h3>满意度评分</h3>
            <div class="stat-number">{{ statData.satisfactionScore }}<small>/5</small></div>
            <div class="stat-trend" :class="statData.satisfactionTrend > 0 ? 'up' : 'down'">
              <el-icon><component :is="statData.satisfactionTrend > 0 ? ArrowUp : ArrowDown" /></el-icon>
              <span>{{ Math.abs(statData.satisfactionTrend) }}%</span>
              <span class="trend-period">较上期</span>
            </div>
          </div>
          <div class="stat-icon satisfaction">
            <el-icon><Star /></el-icon>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 趋势图 -->
      <el-card class="chart-card trend-chart" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>{{ getChartTitle() }}</h3>
            <el-radio-group v-model="trendChartType" size="small">
              <el-radio-button label="line">折线图</el-radio-button>
              <el-radio-button label="bar">柱状图</el-radio-button>
              <el-radio-button label="area">面积图</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="trendChartRef" class="chart-content"></div>
      </el-card>
      
      <!-- 分布图 -->
      <el-card class="chart-card distribution-chart" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>业务类型分布</h3>
            <el-radio-group v-model="distributionChartType" size="small">
              <el-radio-button label="pie">饼图</el-radio-button>
              <el-radio-button label="donut">环形图</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="distributionChartRef" class="chart-content"></div>
      </el-card>
    </div>
    
    <!-- 区域性能对比 -->
    <el-card class="rank-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>区域性能排名</h3>
          <el-radio-group v-model="rankMetric" size="small">
            <el-radio-button label="orderCount">订单数量</el-radio-button>
            <el-radio-button label="revenue">营业额</el-radio-button>
            <el-radio-button label="growth">增长率</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <el-table :data="regionRanking" stripe style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="region" label="区域" min-width="120" />
        <el-table-column prop="orderCount" label="订单数量" min-width="100" sortable>
          <template #default="scope">
            {{ formatNumber(scope.row.orderCount) }}
          </template>
        </el-table-column>
        <el-table-column prop="revenue" label="营业额" min-width="120" sortable>
          <template #default="scope">
            ¥{{ formatNumber(scope.row.revenue) }}
          </template>
        </el-table-column>
        <el-table-column prop="averageValue" label="平均单价" min-width="100">
          <template #default="scope">
            ¥{{ formatNumber(scope.row.averageValue) }}
          </template>
        </el-table-column>
        <el-table-column prop="growth" label="同比增长" min-width="100" sortable>
          <template #default="scope">
            <span :class="scope.row.growth > 0 ? 'text-success' : 'text-danger'">
              {{ scope.row.growth > 0 ? '+' : '' }}{{ scope.row.growth }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="趋势" width="180">
          <template #default="scope">
            <div ref="sparklineRef" :id="`sparkline-${scope.row.id}`" class="sparkline"></div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { 
  Download, ArrowUp, ArrowDown, 
  Money, Tickets, PriceTag, Star
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 筛选相关的状态
const timeRange = ref('month')
const dateRange = ref(null)
const filterForm = reactive({
  region: [],
  businessType: '',
  dimension: 'orderCount'
})

// 图表相关的状态
const trendChartRef = ref(null)
const distributionChartRef = ref(null)
const trendChartType = ref('line')
const distributionChartType = ref('pie')
const rankMetric = ref('orderCount')

// 图表实例
let trendChart: any = null
let distributionChart: any = null

// 模拟的统计数据
const statData = reactive({
  totalOrders: 1283,
  ordersTrend: 12.4,
  totalRevenue: 128560,
  revenueTrend: 15.2,
  averageOrderValue: 98.5,
  aovTrend: 2.8,
  satisfactionScore: 4.7,
  satisfactionTrend: 0.5
})

// 区域排名数据
const regionRanking = ref([
  {
    id: 1,
    region: '华东区域',
    orderCount: 3821,
    revenue: 382100,
    averageValue: 100,
    growth: 8.5,
    trend: [10, 12, 8, 15, 16, 14, 18, 19]
  },
  {
    id: 2,
    region: '华南区域',
    orderCount: 2910,
    revenue: 320100,
    averageValue: 110,
    growth: 12.3,
    trend: [8, 10, 9, 11, 13, 15, 12, 14]
  },
  {
    id: 3,
    region: '华北区域',
    orderCount: 2618,
    revenue: 275890,
    averageValue: 105.4,
    growth: 5.7,
    trend: [12, 14, 10, 9, 11, 13, 15, 12]
  },
  {
    id: 4,
    region: '西南区域',
    orderCount: 1982,
    revenue: 188290,
    averageValue: 95,
    growth: -2.3,
    trend: [15, 12, 10, 8, 7, 9, 6, 8]
  },
  {
    id: 5,
    region: '西北区域',
    orderCount: 1540,
    revenue: 139130,
    averageValue: 90.3,
    growth: 3.1,
    trend: [5, 7, 8, 9, 10, 9, 8, 11]
  },
  {
    id: 6,
    region: '东北区域',
    orderCount: 1375,
    revenue: 130625,
    averageValue: 95,
    growth: -1.8,
    trend: [9, 8, 7, 6, 5, 6, 7, 6]
  }
])

// 区域选项
const regionOptions = [
  {
    value: 'east',
    label: '华东地区',
    children: [
      { value: 'shanghai', label: '上海' },
      { value: 'jiangsu', label: '江苏' },
      { value: 'zhejiang', label: '浙江' },
      { value: 'anhui', label: '安徽' },
      { value: 'fujian', label: '福建' },
      { value: 'jiangxi', label: '江西' },
      { value: 'shandong', label: '山东' }
    ]
  },
  {
    value: 'south',
    label: '华南地区',
    children: [
      { value: 'guangdong', label: '广东' },
      { value: 'guangxi', label: '广西' },
      { value: 'hainan', label: '海南' }
    ]
  },
  {
    value: 'north',
    label: '华北地区',
    children: [
      { value: 'beijing', label: '北京' },
      { value: 'tianjin', label: '天津' },
      { value: 'hebei', label: '河北' },
      { value: 'shanxi', label: '山西' },
      { value: 'neimenggu', label: '内蒙古' }
    ]
  },
  {
    value: 'southwest',
    label: '西南地区',
    children: [
      { value: 'chongqing', label: '重庆' },
      { value: 'sichuan', label: '四川' },
      { value: 'guizhou', label: '贵州' },
      { value: 'yunnan', label: '云南' },
      { value: 'xizang', label: '西藏' }
    ]
  }
]

// 格式化数字
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取图表标题
const getChartTitle = () => {
  const dimensionText = {
    orderCount: '订单数量',
    revenue: '营业额',
    profit: '毛利润',
    customerCount: '客户数量'
  }[filterForm.dimension]
  
  return `${dimensionText}趋势`
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  if (dateRange.value) {
    timeRange.value = 'custom'
  }
}

// 应用筛选
const applyFilter = () => {
  ElMessage.success('筛选条件已应用')
  initCharts()
}

// 重置筛选
const resetFilter = () => {
  filterForm.region = []
  filterForm.businessType = ''
  filterForm.dimension = 'orderCount'
  dateRange.value = null
  timeRange.value = 'month'
  ElMessage.info('筛选条件已重置')
  initCharts()
}

// 导出数据
const exportData = () => {
  ElMessage.success('数据导出中，请稍候...')
  // 实际项目中应当调用API导出数据
  setTimeout(() => {
    ElMessage.success('数据已导出')
  }, 1500)
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }
  
  const xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  const yData = [152, 189, 230, 210, 256, 276, 245, 278, 295, 310, 335, 380]
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['2023年', '2024年']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: trendChartType.value === 'line' ? false : true,
      data: xData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '2023年',
        type: trendChartType.value === 'area' ? 'line' : trendChartType.value,
        areaStyle: trendChartType.value === 'area' ? {} : null,
        data: [120, 132, 101, 134, 90, 230, 210, 180, 190, 234, 260, 310]
      },
      {
        name: '2024年',
        type: trendChartType.value === 'area' ? 'line' : trendChartType.value,
        areaStyle: trendChartType.value === 'area' ? {} : null,
        data: yData
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化分布图表
const initDistributionChart = () => {
  if (!distributionChartRef.value) return
  
  if (!distributionChart) {
    distributionChart = echarts.init(distributionChartRef.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['标准快递', '特快专递', '经济快递', '同城配送', '跨境物流']
    },
    series: [
      {
        name: '业务分布',
        type: 'pie',
        radius: distributionChartType.value === 'donut' ? ['50%', '70%'] : '65%',
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: '标准快递' },
          { value: 735, name: '特快专递' },
          { value: 580, name: '经济快递' },
          { value: 484, name: '同城配送' },
          { value: 300, name: '跨境物流' }
        ]
      }
    ]
  }
  
  distributionChart.setOption(option)
}

// 初始化迷你趋势图
const initSparklines = () => {
  // 为每个区域行渲染迷你趋势图
  regionRanking.value.forEach(region => {
    const el = document.getElementById(`sparkline-${region.id}`)
    if (!el) return
    
    const sparkChart = echarts.init(el)
    const option = {
      xAxis: {
        type: 'category',
        show: false
      },
      yAxis: {
        type: 'value',
        show: false
      },
      grid: {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0
      },
      series: [
        {
          data: region.trend,
          type: 'line',
          showSymbol: false,
          lineStyle: {
            color: region.growth > 0 ? '#67C23A' : '#F56C6C'
          },
          areaStyle: {
            color: region.growth > 0 ? 'rgba(103, 194, 58, 0.2)' : 'rgba(245, 108, 108, 0.2)'
          }
        }
      ]
    }
    sparkChart.setOption(option)
  })
}

// 初始化所有图表
const initCharts = () => {
  initTrendChart()
  initDistributionChart()
  
  // 添加一点延迟，确保DOM已更新
  setTimeout(() => {
    initSparklines()
  }, 100)
}

// 监听图表类型变化，更新图表
watch([trendChartType, distributionChartType], () => {
  initCharts()
})

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  trendChart?.resize()
  distributionChart?.resize()
})

onMounted(() => {
  initCharts()
})
</script>

<style scoped>
.stats-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.filter-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.card-header h2, .card-header h3 {
  margin: 0;
  font-weight: 600;
}

.card-header h2 {
  font-size: 18px;
}

.card-header h3 {
  font-size: 16px;
  color: #606266;
}

.filter-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-form {
  margin-top: 15px;
}

/* 统计卡片样式 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  height: 120px;
  margin-bottom: 0;
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.stat-info {
  flex: 1;
}

.stat-info h3 {
  color: #909399;
  font-size: 14px;
  margin: 0 0 8px 0;
  font-weight: 400;
}

.stat-number {
  font-size: 26px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
}

.stat-number small {
  font-size: 16px;
  font-weight: 400;
  color: #909399;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1;
}

.stat-trend.up {
  color: #67C23A;
}

.stat-trend.down {
  color: #F56C6C;
}

.trend-period {
  color: #909399;
  margin-left: 5px;
  font-size: 12px;
}

.stat-icon {
  width: 55px;
  height: 55px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
}

.stat-icon.orders {
  background: linear-gradient(135deg, #409EFF, #007AFF);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #67C23A, #42B983);
}

.stat-icon.aov {
  background: linear-gradient(135deg, #E6A23C, #F56C6C);
}

.stat-icon.satisfaction {
  background: linear-gradient(135deg, #9966FF, #6A5ACD);
}

/* 图表区域样式 */
.charts-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.chart-card {
  margin-bottom: 0;
}

.chart-content {
  height: 350px;
}

/* 排名表格样式 */
.rank-card {
  margin-bottom: 0;
}

.text-success {
  color: #67C23A;
}

.text-danger {
  color: #F56C6C;
}

.sparkline {
  width: 100%;
  height: 30px;
}

@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .stat-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}
</style> 